package com.chinacoal.microservice.impl.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.api.WorkflowClient;
import com.chinacoal.microservice.api.model.ApproveTaskParam;
import com.chinacoal.microservice.api.model.ForeignTaskParam;
import com.chinacoal.microservice.api.model.resource.*;
import com.chinacoal.microservice.impl.client.CCIPTaskClient;
import com.chinacoal.microservice.impl.service.CCIPTaskService;
import com.chinacoal.microservice.model.wofkflow.entity.ApprovalHistoryEntity;
import com.chinacoal.microservice.util.result.CodeMsg;
import com.chinacoal.microservice.util.result.Result;
import com.chinacoal.microservice.util.tool.DateTools;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 门户协同平台 获得待办详情服务
 *
 * @author: YunTao.Li
 * @create: 2020-06-07 10:01
 * @description:
 **/
@Service
public class CCIPTaskServiceImpl implements CCIPTaskService {

    @Resource
    private WorkflowClient workflowClient;

    @Autowired
    private CCIPTaskClient ccipTaskClient;

    /**
     * 获得待办详情
     *
     * @param foreignTaskParam :
     * @return : com.chinacoal.microservice.util.result.Result<com.chinacoal.microservice.api.model.resource.BusinessData>
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    @Override
    public Result<BusinessData> getDetails(ForeignTaskParam foreignTaskParam) throws Exception {
        String bizCode = foreignTaskParam.getBizCode();
        Result<BusinessData> businessData = null;
        businessData = this.buildCCIPTaskBizData(foreignTaskParam);

        return businessData;
    }

    /**
     * 审批通过
     *
     * @param bizID   :
     * @param bizCode :
     * @return : void
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    @Override
    public void approve(String bizID, String bizCode, ApproveTaskParam approveTaskParam) throws Exception {
        String taskId = approveTaskParam.getSysTaskId();
        String instanceCurrentState = approveTaskParam.getInstanceCurrentState();

        Map record = new HashMap();
        record.put("taskId", taskId);
        record.put("instanceCurrentState",instanceCurrentState);

        System.out.println("call approve bizID:" + bizID + "bizCode:" + bizCode + " taskId:" + taskId);

        // 根据不同的类型执行不同的填充方法
        if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_LEAVE)) { // 请假单
            ccipTaskClient.leaveApprove(bizID, record);
        } else if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_TRAVEL)) { // 因公外出申请单
            ccipTaskClient.travelApprove(bizID, record);
        } else if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_APPEAL)) { // 考勤申诉单
            ccipTaskClient.appealApprove(bizID, record);
        } else {

        }
    }

    /**
     * 审批驳回
     *
     * @param bizID   :
     * @param bizCode :
     * @return : void
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    @Override
    public void approveDisagree(String bizID, String bizCode, ApproveTaskParam approveTaskParam) throws Exception {
        String taskId = approveTaskParam.getSysTaskId();

        Map record = new HashMap();
        record.put("taskId", taskId);

        System.out.println("call approveDisagree bizID:" + bizID + "bizCode:" + bizCode + " taskId:" + taskId);
        // 根据不同的类型执行不同的填充方法
        if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_LEAVE)) { // 请假单
            ccipTaskClient.leaveApproveDisagree(bizID, record);
        } else if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_TRAVEL)) { // 因公外出申请单
            ccipTaskClient.travelApproveDisagree(bizID, record);
        } else if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_APPEAL)) { // 考勤申诉单
            ccipTaskClient.appealApproveDisagree(bizID, record);
        } else {

        }
    }

    /**
     * @param foreignTaskParam :
     * @return : com.chinacoal.microservice.util.result.Result<com.chinacoal.microservice.api.model.resource.BusinessData>
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    private Result<BusinessData> buildCCIPTaskBizData(ForeignTaskParam foreignTaskParam) throws Exception {
        String bizID = foreignTaskParam.getBusinessId();
        String bizCode = foreignTaskParam.getBizCode();

        System.out.println("ready to call ccipTaskClient bizCode:" + bizCode + " bizID:" + bizID);
        Map busiResult = ccipTaskClient.getTaskInfo(bizCode, bizID);
        System.out.println("busiResult:" + busiResult);
        Iterator entries = busiResult.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            System.out.println("Key = " + key + ", Value = " + value);
        }

        Map recordData = (Map) busiResult.get("data");
        String processInstID = recordData.get("insCode").toString();

        //封装数据对象
        BusinessData businessData = new BusinessData();
        FormCanvasData canvasData = null;

        // 根据不同的类型执行不同的填充方法
        if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_LEAVE)) { // 请假单
            canvasData = this.ccipLeaveRecordFiller(recordData);
        } else if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_TRAVEL)) { // 因公外出申请单
            canvasData = this.ccipTravelRecordFiller(recordData);
        } else if (StringUtils.equalsIgnoreCase(bizCode, UnionTaskVar.APP_CCMS_HR_APPEAL)) { // 考勤申诉单
            canvasData = this.ccipAppealRecordFiller(recordData);
        } else {

        }

        businessData.addFormCanvasData(canvasData);

        // 获取审核信息
        Result<Page<ApprovalHistoryEntity>> historyInfoResult = workflowClient.getApprovalHistory(0, Integer.MAX_VALUE, Long.valueOf(processInstID));
        if (historyInfoResult.getCode() != 10000) {
            return Result.error(CodeMsg.SERVER_ERROR.fillArgs("调用工作流获取审批历史服务端异常： " + historyInfoResult.getMsg()));
        }

        //封装审核信息
        this.buildApprovalRecords(businessData, historyInfoResult);

        // 封装审核按钮
        this.buildButtonInfo(businessData);

        // 返回信息
        DictionaryCanvasData resultInfo = new DictionaryCanvasData();
        businessData.setResultInfo(resultInfo);

        return Result.success(businessData);
    }

    /**
     * 构建审核历史信息
     */
    private void buildApprovalRecords(BusinessData businessData, Result<Page<ApprovalHistoryEntity>> historyInfoResult) throws Exception {
        TableCanvasData approvalRecords = new TableCanvasData();
        approvalRecords.setName("审批记录");
        List<ApprovalHistoryEntity> historyList = historyInfoResult.getData().getRecords();
        if (CollectionUtils.isNotEmpty(historyList)) {
            for (int i = 0; i < historyList.size(); i++) {
                ApprovalHistoryEntity entity = historyList.get(i);
                RecordData advise = new RecordData();
                advise.add("opinion", "审核意见", entity.getApprovalOpinion());
                advise.add("handler", "审核人姓名", entity.getActivityUserName());
                advise.add("handlerId", "审核人ID", entity.getActivityUser() == null ? "" : entity.getActivityUser() + "");
                advise.add("handlerDate", "审核时间", DateTools.dateToString(entity.getStartDate(), "yyyy-MM-dd HH:mm:ss"));
                advise.add("activityName", "审核环节", entity.getActivityName());
                advise.add("handlerStatus", "审批结果", entity.getOpcodeName());
                approvalRecords.add(advise);
            }
        }
        businessData.setApprovalRecords(approvalRecords);
    }

    /**
     * 构建审核按钮
     */
    private void buildButtonInfo(BusinessData businessData) {
        DictionaryCanvasData buttonInfo = new DictionaryCanvasData();
        buttonInfo.add("同意", "1000");
        buttonInfo.add("驳回", "1001");
        businessData.setButtonInfo(buttonInfo);
    }

    public static void main(String[] args) {
        String startDateStr = "";
        String endDateStr = "";
        try{
//            String startDateUnix = recordData.get("startDate").toString();
//            startDateStr = new SimpleDateFormat("yyyy-MM-dd").format(startDateUnix);

            Double endDateUnix = Double.parseDouble("1593532800000");
            endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(endDateUnix);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 填充请假单字段
     *
     * @return : com.chinacoal.microservice.api.model.resource.FormCanvasData
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    private FormCanvasData ccipLeaveRecordFiller(Map recordData) {
        // 字典转换
        String holidayTypeKey = recordData.get("holidayType").toString();
        String holydayTypeValue = this.getDictValueHolidayType(holidayTypeKey);

        String startTimeTypeKey = recordData.get("startTimeType").toString();
        String startTimeTypeValue = this.getDictValueTimeType(startTimeTypeKey);

        String endTimeTypeKey = recordData.get("endTimeType").toString();
        String endTimeTypeValue = this.getDictValueTimeType(endTimeTypeKey);

        String isLeaveBjKey = recordData.get("isLeaveBj").toString();
        String isLeaveBjValue = this.getDictValueIsLeaveBJ(isLeaveBjKey);

        //时间戳转换
        String startDateStr = "";
        String endDateStr = "";
        try{
            double startDateUnix = Double.parseDouble(recordData.get("startDate").toString());
            startDateStr = new SimpleDateFormat("yyyy-MM-dd").format(startDateUnix);

            double endDateUnix = Double.parseDouble(recordData.get("endDate").toString());
            endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(endDateUnix);
        }catch (Exception e){
            e.printStackTrace();
        }



        FormCanvasData canvasData = new FormCanvasData();
        canvasData.setName("请假单");
        canvasData.add("假期类型", holydayTypeValue);
        canvasData.add("申请单编码", recordData.get("leaveCode").toString());
        canvasData.add("员工姓名", recordData.get("empName").toString());
        canvasData.add("员工编码", recordData.get("empCode").toString());
        canvasData.add("所属机构", recordData.get("orgName").toString());
        canvasData.add("所属部门", recordData.get("deptName").toString());
        canvasData.add("开始日期", startDateStr);
        canvasData.add("开始时段", startTimeTypeValue);
        canvasData.add("结束日期", endDateStr);
        canvasData.add("结束时段", endTimeTypeValue);
        canvasData.add("请假天数", recordData.get("days").toString());
        canvasData.add("联系电话", recordData.get("telephone").toString());
        canvasData.add("去向", recordData.get("position").toString());
        canvasData.add("是否离京", isLeaveBjValue);
        canvasData.add("离京时间", "");
        canvasData.add("回京时间", "");
        canvasData.add("请假事由", recordData.get("leaveDesc").toString());

        System.out.println("请假单:" + recordData);
        return canvasData;
    }

    /**
     * 填充因公差旅单字段
     *
     * @return : com.chinacoal.microservice.api.model.resource.FormCanvasData
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    private FormCanvasData ccipTravelRecordFiller(Map recordData) {
        String trafficKey = recordData.get("traffic").toString();
        String trafficValue = this.getDictValueTraffic(trafficKey);

        String backTrafficKey = recordData.get("backTraffic").toString();
        String backTrafficValue = this.getDictValueTraffic(backTrafficKey);

        //时间戳转换
        String startDateStr = "";
        String endDateStr = "";
        try{
            double startDateUnix = Double.parseDouble(recordData.get("startDate").toString());
            startDateStr = new SimpleDateFormat("yyyy-MM-dd").format(startDateUnix);

            double endDateUnix = Double.parseDouble(recordData.get("endDate").toString());
            endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(endDateUnix);
        }catch (Exception e){
            // do nothing;
        }

        FormCanvasData canvasData = new FormCanvasData();
        canvasData.setName("因公外出申请单");
        canvasData.add("申请单编码", recordData.get("bizTravelCode").toString());
        canvasData.add("开始日期", startDateStr);
        canvasData.add("结束日期", endDateStr);
        canvasData.add("员工姓名", recordData.get("empName").toString());
        canvasData.add("员工编码", recordData.get("empCode").toString());
        canvasData.add("所属机构", recordData.get("orgName").toString());
        canvasData.add("所属部门", recordData.get("deptName").toString());
        canvasData.add("交通工具", trafficValue);
        canvasData.add("返回交通工具", backTrafficValue);
        canvasData.add("出差路线", recordData.get("trace").toString());
        canvasData.add("出差天数", recordData.get("days").toString());
        canvasData.add("出差待办事由", recordData.get("travelDesc").toString());
        System.out.println("因公外出申请单:" + recordData);
        return canvasData;
    }

    /**
     * 填充考勤申诉字段
     *
     * @return : com.chinacoal.microservice.api.model.resource.FormCanvasData
     * @author : YunTao.Li
     * @date : 2020/6/7 2020/6/7
     */
    private FormCanvasData ccipAppealRecordFiller(Map recordData) {
        FormCanvasData canvasData = new FormCanvasData();
        canvasData.setName("考勤申诉单");
        canvasData.add("申请单编码", recordData.get("explainCode").toString());
        canvasData.add("申诉人", recordData.get("empName").toString());
        canvasData.add("所属机构", recordData.get("orgName").toString());
        canvasData.add("所属部门", recordData.get("deptName").toString());
        canvasData.add("所属年月", recordData.get("periodCode").toString());
        System.out.println("考勤申诉单:" + recordData);
        return canvasData;
    }


    //TODO:匹配字典项
    private String getDictValueHolidayType(String key){
        key = StringUtils.isBlank(key) ? "0" : key;
        int keyIndex = Integer.parseInt(key);
        String[] holidayTypes = {"空","事假","病假","年休假","产假","婚假","哺乳假","丧假","探亲假","工伤假","培训考试假","公假"};
        return holidayTypes[keyIndex];
    }

    //TODO:匹配字典项
    private String getDictValueTimeType(String key){
        int keyIndex = Integer.parseInt(key);
        String[] holidayTypes = {"空","上午","下午","全天"};
        return holidayTypes[keyIndex];
    }

    //TODO:匹配字典项
    private String getDictValueTraffic(String key){
        int keyIndex = Integer.parseInt(key);
        String[] holidayTypes = {"空","飞机","火车","大巴","自驾"};
        return holidayTypes[keyIndex];
    }

    //TODO:匹配字典项
    private String getDictValueIsLeaveBJ(String key){
        key = StringUtils.isBlank(key) ? "0" : key;
        int keyIndex = Integer.parseInt(key);
        String[] holidayTypes = {"否","是"};
        return holidayTypes[keyIndex];
    }
}
